<?php

namespace App\Models\V1;

use Carbon\Carbon;
use DB;
use Illuminate\Database\Eloquent\Model;

class MemberModel extends Model
{
    protected $table      = 'memberinfo';

    public    $timestamps = false;
    protected $fillable=['AppKey'];
    
    static    $tb_member  = "memberinfo";   //会员表
    private   $defaultHeadImg;

    public function __construct()
    {
        $this->defaultHeadImg = env('API_HOST') . "/images/default-images/default-head-img.png";
    }

    /**
     * 注册用户
     * @param 用户数据信息|array $data
     * @return intergel 用户ID
     * @internal param 用户数据信息 $data
     */
    public function register(array $data)
    {
        if(!isset($data['MemNumber']))
        {
            do{
                $memberNumber   = create_member_number();
                $tempInfo       = $this->get_member_info_by_member_number($memberNumber);
            }while($tempInfo);

        }else{
            $memberNumber     = $data['MemNumber'];
        }

        $dateTime       = date_time();
        $colums         = [
            "States"        => 0,
            "MemNumber"     => $memberNumber,
            "UserName"      => "",
            "YourName"      => "",
            "NickName"      => "",
            "UserPassWord"  => "",
            "FilePath1"     => "",
            "WeiXID"        => "",
            "VipNumber"     => 1,
            "MemIntegral"   => 0,
            "LoginKey"      => "",
            "MemEndTime"    => "",
            "personal_end_time" => "",
            "AppKey"        => "",
            "RegisterType"  => "后台导入",
            "DeleteMark"    => 1,
            "ReleaseDate"   => $dateTime,
            "AddDate"       => $dateTime,
            "city"          => 0,
            'sex'           => 'N',
            'app_openid'    => '',
            'wx_unionid'    => ''
        ];


        foreach($colums as $k=>$v)
        {
            $colums[$k] = isset($data[$k]) ? $data[$k] : $v;
        }

        $userId = DB::table(self::$tb_member)->insertGetId($colums);

        return $userId;
    }

    /**
     * 获取用户信息
     * @param string mobile 用户的手机号
     * @param string appKey 用户的设备ID
     * @param boolean siVip 是否是VIP
     * @return Object
     * */
    public function get_member_info_by_mobile_key($mobile, $appKey, $isVip = false)
    {
        $memberInfo = $this->get_member_base_info($mobile, $appKey, $isVip);
        if ($memberInfo) {
            unset($memberInfo->UserPassWord);
            unset($memberInfo->LoginKey);
            //unset($memberInfo->AppKey);

            $memberInfo->FilePath1 = change_member_head_img($memberInfo->FilePath1);
            $memberInfo->headImg   = $memberInfo->FilePath1;
            $memberInfo->isValid   = $this->judge_member_is_valid($memberInfo);
            $memberInfo->alias     = $memberInfo->UserName;
        } else {
            $memberInfo = false;
        }

        return $memberInfo;
    }

    /**
     * 根据类型获取用户信息
     * @param string $key 字段名称
     * @
     * */
    public function get_member_info_by_type($key, $value)
    {

    }

    /**
     * 获取用户的基本信息
     * */
    public function get_member_base_info($mobile, $appKey, $isVip)
    {
        $memberInfo = DB::table(self::$tb_member)
            ->where('UserName', $mobile)
            ->where('AppKey', $appKey)
            ->where('DeleteMark', 1);
        $isVip ? $memberInfo = $memberInfo->where('States', 1) : '';
        $memberInfo = $memberInfo->first();

        return $memberInfo;
    }

    /**
     * 根据会员编号获取会员信息
     * */
    public function get_member_info_by_member_number($memberNumber)
    {
        $info = DB::table(self::$tb_member)
            ->where('MemNumber', $memberNumber)
            ->where('DeleteMark', 1)
            ->first();

        if (!$info) {
            $memberInfo = false;
        } else {
            $memberInfo = $this->get_member_info_by_mobile_key($info->UserName, $info->AppKey);
        }

        return $memberInfo;
    }

    /**
     * 根据手机号获取用户信息
     * */
    public function get_member_info_by_mobile($mobile)
    {
        $memberInfo = DB::table(self::$tb_member)
            ->select('AppKey')
            ->where('UserName', $mobile)
            ->where('DeleteMark', 1)
            ->first();
        if (!$memberInfo) {
            $memberInfo = false;
        } else {
            $memberInfo = $this->get_member_info_by_mobile_key($mobile, $memberInfo->AppKey);
        }

        return $memberInfo;
    }


    /**
     * 根据ID获得用户信息
     * @param userId 会员ID
     * */
    public function get_member_info_by_id($userId)
    {
        $memberInfo = DB::table(self::$tb_member)
            ->where('UserID', $userId)
            ->first();

        if ($memberInfo) {
            $memberInfo->FilePath1 = change_member_head_img($memberInfo->FilePath1);
        }

        return $memberInfo;
    }

    /**
     * 根据微信的unionId来获取用户信息
     * @param   string $unionId 微信开放平台unionId
     * @return  object
     * */
    public function get_member_info_by_unionid($unionId)
    {
        $memberInfo = DB::table(self::$tb_member)
            ->where("DeleteMark", 1)
            ->where("wx_unionid", $unionId)
            ->first();

        if ($memberInfo) {
            $memberInfo->FilePath1 = change_member_head_img($memberInfo->FilePath1);
        } else {
            $memberInfo = false;
        }

        return $memberInfo;
    }


    /**
     * 获取用户的标签
     * */
    public function get_member_tags($userId)
    {
        $tags = DB::table('member_tag')->where('user_id', $userId)->pluck('tag_name');
        $tags = $tags ? $tags : [];

        return $tags;
    }


    /**
     * 判断用户是否有效
     *
     * */
    public function judge_member_is_valid($memberInfo)
    {
        $nowtime = date_time();
        $endtime = $memberInfo->MemEndTime;
        if ($memberInfo && $memberInfo->States == 1) {
            if (strtotime($nowtime) <= strtotime($endtime)) {
                return true;
            }
        }

        return false;
    }


    /**
     * 添加意见反馈
     * @arrSuggestion array $arrSuggestion 用户提交的建议信息
     * @return Object
     * */
    public function add_suggestion($arrSuggestion)
    {
        $date   = date_time();
        $data   = [
            'States'      => 0,
            'DeleteMark'  => 1,
            'ReleaseDate' => $date,
            'AddDate'     => $date,
        ];
        $data   = array_merge($arrSuggestion, $data);
        $result = DB::table('suggestion')->insert($data);

        return $result;
    }


    /**
     * 更新会员信息
     * @param array $arrMemberInfo 会员信息,其中必须包含两项之一 memberNumber或userid
     * @return Object
     * */
    public function update_member_info($arrMemberInfo)
    {
        $source = DB::table('memberinfo');
        if (isset($arrMemberInfo['UserID'])) {
            $source = $source->where('UserID', $arrMemberInfo['UserID']);
            unset($arrMemberInfo['UserID']);
        } elseif (isset($arrMemberInfo['MemNumber'])) {
            $source = $source->where('MemNumber', $arrMemberInfo['MemNumber']);
            unset($arrMemberInfo['MemNumber']);
        } else {
            return false;
        }
        $result = $source->update($arrMemberInfo);

        return $result;
    }


    /**
     * 改变用户的结束时间，必须在用户加入企业或移除后再调用
     * @param integer $userId 用户ID
     * */
    public function change_member_endtime($userId)
    {

        $sql = "SELECT  b.company_id,b.vip_end_date
              FROM      company_user a
              LEFT JOIN company b ON  b.company_id = a.company_id
              WHERE     a.user_id   = $userId
              AND       a.is_delete = 0
              AND       a.is_delete = 0
              GROUP BY  b.company_id ";
        $info   = DB::select($sql);
        $memberInfo = $this->get_member_info_by_id($userId);
        //计算所有时间的最大值
        $endTimes   = [strtotime($memberInfo->personal_end_time)];
        foreach($info as $v)
        {
            array_push($endTimes,strtotime($v->vip_end_date));
        }
        $maxTime    = current_date(max($endTimes));
        $this->update_member_info(['UserID'=>$userId,'MemEndTime'=>$maxTime]);
    }

    /**
     * 获得会员学习官关系信息
     * */
    public function get_member_drp_info($userId)
    {
        $sql
              = "SELECT
                b.MemNumber,
                b.SalesMoney,
                b.MemBalances,
                b.FinishMoney,
                b.DRPLevel,
                b.IDTree,
                b.ParentID,
                b.DRPID
        FROM memberinfo as a
        LEFT JOIN memberdrp as b ON  b.MemNumber = a.MemNumber AND  b.DeleteMark = 1
        WHERE a.UserID = $userId
        limit 1";
        $info = DB::select($sql);
        return $info[0];
    }


    /**
     * 绑定微信信息
     * @param integer $userId 用户ID
     * @param string $unionId 微信联合ID
     * @param string $openId 微信openId,
     * @param boolean $isGongzhonghao 是否是公众号
     * @param string $wxName 微信名称
     * @param string $headImg 头像图片
     * @return boolean
     * */
    public function bind_wx_info($userId, $unionId, $openId, $isGongzhonghao = true, $wxName = "", $headImg = "")
    {

        $data['wx_unionid'] = $unionId;
        $data['UserID']     = $userId;

        $wxName ? $data['NickName'] = $wxName : "";
        $headImg ? $data['head_img'] = $headImg : "";
        $isGongzhonghao ? $data['WeiXID'] = $openId : $data['app_openid'] = $openId;

        //删除 临时的ID

        DB::table('memberinfo')
            ->where('wx_unionid', $unionId)
            ->where('UserID', '<>', $userId)
            ->update(['DeleteMark' => 0]);


        //修改用户信息
        $this->update_member_info($data);

        return true;
    }

    public function get_user_famous_info($readPartId, $type, $userId)
    {
        $data            = DB::table('memberinfo as m')
            ->select('YourName', 'FilePath1', 'fl.integral', DB::raw('count(bsp.MemNumber) as readBookAmount'), 'fl.watch_video_time', 'fl.last_week_rank', 'fl.flower_' . $type)
            ->leftJoin('read_party_member as rpm', 'rpm.user_id', '=', 'm.UserID')
            ->leftJoin('booksumup as bsp', 'bsp.MemNumber', '=', 'm.MemNumber')
            ->leftJoin('flower_list as fl', 'fl.user_id', '=', 'm.UserID')
            ->orderBy('fl.integral')
            ->groupBy('m.MemNumber')
            ->where(['m.DeleteMark' => 1, 'rpm.read_party_id' => $readPartId, 'bsp.is_delete' => 0, 'm.UserID' => $userId, 'fl.is_show' => 0])
            ->first();
        $data->FilePath1 = change_member_head_img($data->FilePath1);

        return $data;
    }


    public function famous_list($readPartId, $type, $user_id)
    {
        $data = DB::table('memberinfo as m')
            ->select('YourName', 'm.UserID', 'FilePath1', 'fl.integral', DB::raw('count(bsp.MemNumber) as readBookAmount'), 'fl.watch_video_time', 'fl.last_week_rank', 'fl.flower_' . $type)
            ->leftJoin('booksumup as bsp', 'bsp.MemNumber', '=', 'm.MemNumber')
            ->leftJoin('read_party_member as rpm', 'rpm.user_id', '=', 'm.UserID')
            ->leftJoin('flower_list as fl', 'fl.user_id', '=', 'm.UserID')
            ->orderBy('fl.integral', 'desc')
            ->groupBy('m.MemNumber')
            ->where(['m.DeleteMark' => 1, 'bsp.is_delete' => 0, 'rpm.read_party_id' => $readPartId])
            ->get();

        foreach ($data as $k => $v) {
            $v->FilePath1 = change_member_head_img($v->FilePath1);
            $v->rank      = $k + 1;
            $user_ids     = explode(',', $v->{'flower_' . $type});
            if ($key = array_search($user_id, $user_ids)) {
                $v->is_flower = 1;//已经送过花了
            } else {
                $v->is_flower = 0;//没有送过花
            }
        };

        return $data;
    }
}